package com.rayframework.boot.helper;


import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.ray.tool.file.RayFileTools;
import com.rayframework.boot.config.ApplicationConfig;

import com.rayframework.context.utils.ApplicationConfigUtils;
import com.rayframework.context.utils.RayConsoleUtils;
import com.rayframework.context.utils.RayContextUtils;
import com.rayframework.core.common.constant.RayCoreConstants;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * // TODO 记得给名字
 *
 * @author LiaoYuXing-Ray
 * @version 1.0
 * @createDate 2023/9/26 17:24
 **/
public class RayMyBatisPlusHelper {
    /**
     * 初始化标记 2023/9/12 15:32
     */
    private static boolean isInitialized = false;

    private static SqlSessionFactory sqlSessionFactory;


    /**
     * 此处初始化在 {@link ApplicationConfig} 中
     *
     * @author LiaoYuXing-Ray 2023/9/12 16:03
     **/
    public static void init() {
        if (!isInitialized) {
            // 此处再检查一次，双重保险
            if (!checkUse()) {
                return;
            }
            try (FileInputStream fis = new FileInputStream(RayFileTools.pathCombine(1,
                    ApplicationConfigUtils.getAppRoot()
                    , "src", "main", "resources", RayCoreConstants.DB_XML))) {
                // 打印sql日志
                if (RayContextUtils.checkProperty("Ray.init.MyBatisPlus.log.print")) {
                    LogFactory.useStdOutLogging();
                }

                // 创建 MyBatisPlus 的 SqlSessionFactory 实例
                sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(fis);
                if (sqlSessionFactory == null) {
                    throw new IOException("SqlSessionFactory创建失败！");
                }
            } catch (IOException e) {
                RayConsoleUtils.error("读取配置文件[" + RayCoreConstants.DB_XML + "]失败，请配置数据源！" + e.getMessage());
            }
            // 标记已经初始化
            isInitialized = true;
        }

    }


    public static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            if (!checkUse()) {
                return null;
            }
            init();
        }
        return sqlSessionFactory;
    }

    /**
     * 添加 Mapper 类到 SqlSessionFactory
     *
     * @param mapperClass 要添加的 Mapper 类
     * @author LiaoYuXing-Ray 2023/9/8 11:04
     **/
    public static void addMapper(Class<?> mapperClass) {
        if (!checkUse()) {
            return;
        }
        // 将 Mapper 类添加到 SqlSessionFactory 的配置中
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
    }

    public static SqlSession getSqlSession() {
        return getSqlSession(true);// true表示自动提交事务
    }

    public static SqlSession getSqlSession(boolean flag) {
        if (!checkUse()) {
            return null;
        }
        if (sqlSessionFactory != null) {
            return sqlSessionFactory.openSession(flag);// true表示自动提交事务
        }
        return null;
    }

    public static void commitSqlSession(SqlSession session) {
        if (session != null) {
            session.commit();
            session.close();
        }
    }

    public static void rollbackSqlSession(SqlSession session) {
        if (session != null) {
            session.rollback();
            session.close();
        }
    }

    public static void closeSqlSession(SqlSession session) {
        if (session != null) {
            session.close();
        }
    }


    /**
     * 检查设置中是否使用 MyBatisPlus 并输出警告
     *
     * @return boolean true为使用，false为不使用
     * @author LiaoYuXing-Ray 2023/9/12 16:10
     **/
    private static boolean checkUse() {
        return RayContextUtils.checkPropertyUse("Ray.init.MyBatisPlus.use");
    }


    /**
     * 初始化配置
     *
     * @param configuration
     */
//    private void initConfiguration(MybatisConfiguration configuration) {
//        //开启驼峰大小写转换
//        configuration.setMapUnderscoreToCamelCase(true);
//        //配置添加数据自动返回数据主键
//        configuration.setUseGeneratedKeys(true);
//    }

    /**
     * 初始化拦截器
     *
     * @return
     */
//    private Interceptor initInterceptor() {
//        //创建mybatis-plus插件对象
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        //构建分页插件
//        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
//        paginationInnerInterceptor.setDbType(DbType.MYSQL);
//        paginationInnerInterceptor.setOverflow(true);
//        paginationInnerInterceptor.setMaxLimit(500L);
//        interceptor.addInnerInterceptor(paginationInnerInterceptor);
//        return interceptor;
//    }


}

